<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/10/19
 * Time: 14:22
 */

namespace app\controller\index;
use app\model\index\User AS model;
use app\model\UserAmount AS amount;
use think\facade\Db;

class Users extends Base
{
    protected $size = 15;

    public function count(){
        $count = model::where('status',3)->count();
        return $this->msg(['shengqi' => $count]);
    }

    public function list(){
        $where = [];
        $list = model::where('pid',0)
            ->where($where)
            ->order('status DESC,login_time DESC')
            ->paginate([
                'page' => $this->page,
                'list_rows' => $this->size
            ]);
        return $this->view('/index/users/list',['list' => $list]);
    }

    public function info($id){
        $info = model::find($id);
        return $this->msg($info);
    }

    public function create(){
        $post = input('post.');
        if (empty($post['username']) || empty($post['password']))
            return $this->fail('密码和账号是必填项必须填写');
        $find = Db::name('user')->where('username',$post['username'])->find();
        if (!empty($find['id'])) {
            if (empty($find['delete_time']))
                return $this->fail('账号已经存在');
            else {
                $post['delete_time'] = null;
                model::find($find['id'])->save($post);
            }
        }
        model::create($post);
        return $this->msg();
    }

    public function del($id){
        model::where('id',$id)->save(['delete_time' => date('Y-m-d')]);
        return $this->msg();
    }

    public function save($id){
        $info = model::find($id);
        $post = input('post.');
        if (!empty($post['attr'])) {
            if ($post['attr'] == 'amount') {
                if ($post['value'] > $info->amount) {
                    $amount = $post['value'] - $info->amount;
                } else {
                    $amount = $info->amount - $post['value'];
                    $amount = $amount * -1;
                }
                amount::create([
                    'before_amount' => $info->amount,
                    'after_amount' => $post['value'],
                    'amount' => $amount,
                    'user_id' => $info->id,
                    'pid' => $info->pid,
                    'type' => 2,
                    'order_no' => '99' . date('YmdHis') . rand(1000, 9999)
                ]);
            }
            $is_save = $info->save([$post['attr'] => $post['value']]);
        }else{
            $info->data($post);
            $is_save = $info->save();
        }
        if ($is_save){
            return $this->msg();
        }else{
            return $this->fail();
        }
    }
}